import json,re,random
from django.contrib.auth import login as Login, logout
from django.shortcuts import render, redirect,reverse
from django.http import HttpResponse,HttpResponseForbidden
from django.views import View
from django_redis import get_redis_connection


# Create your views here.
import logging

from users.models import Users

logger = logging.getLogger('django')

def hello(requset):

    return HttpResponse('hello word')




# 在线课堂
def course(request):
    title = '在线课堂'
    return render(request,'course/course.html',context={'title':title})

# 下载文档
def docDownload(request):
    title = '下载文档'
    return  render(request,'doc/docDownload.html',context={'title':title})

# 搜索
def search(request):
    title = '搜索'
    return  render(request,'news/search.html',context={'title':title})


#注册
from dj31.utils.response import res_json, Code, error_map
class RegisterView(View):
    def get(self,request):
        return render(request, 'users/register.html')

    def post(self,requset):
        js_str = requset.body
        if not js_str:
            res_json(errno=Code.PARAMERR,errmsg=error_map[Code.PARAMERR])
        dict_data = json.loads(js_str)
        username=dict_data.get('username')
        password=dict_data.get('password')
        password_repeat=dict_data.get('password_repeat')
        mobile=dict_data.get('mobile')
        sms_code=dict_data.get('sms_code')

        #判断是否为空
        if not all([username,password,password_repeat,mobile,sms_code]):
            return HttpResponseForbidden('请填写准确参数')

        #用户名
        if not re.match('^\w{5,20}$',username):
            return HttpResponseForbidden('用户名输入错误')

        if Users.object.filter(username=username).count() > 0:#判断是否存在，存在返回1

            return res_json(errmsg='用户名已存在')

        #密码
        if not re.match('^[0-9A-Za-z]{6,20}$', password):
            return HttpResponseForbidden('密码输入有误')
        if password != password_repeat:
            return res_json(errmsg='两次密码不一致')

        #手机号
        if not re.match('^1[358]\d{9}$', mobile):
            return res_json(errmsg='手机号输入错误')
        if Users.object.filter(mobile=mobile).count() > 0:#判断是否存在，存在返回1
            return HttpResponseForbidden('手机号已存在')

        #手机验证码
        redis_conn = get_redis_connection('verify')
        sms_code_serve = redis_conn.get('sms_' +mobile)

        #判断是否为空
        if sms_code_serve is None:
            return res_json(errno=Code.PARAMERR,errmsg='验证码过期')

        #用完就丢
        redis_conn.delete('sms_'.format(mobile))
        redis_conn.delete('sms_flag_{}'.format(mobile))

        #判断是否
        if sms_code != sms_code_serve.decode():  #b字节，要解码
            return HttpResponseForbidden('短信验证码错误')

        #创建用户
        user = Users.object.create_user(username=username,password=password,mobile=mobile)

        #保持连接
        Login(requset,user)

        return res_json(errno=Code.OK,errmsg='注册成功')

#表单
from .forms import LoginForm

#登陆
class LoginView(View):
    def get(self,request):
        title = '登录界面'
        return render(request,'users/login.html',context={'title':title})

    def post(self,request):
        js_str = request.body
        if not js_str:
            res_json(errno=Code.PARAMERR,errmsg=error_map[Code.PARAMERR])
        dict_data = json.loads(js_str.decode())  #json转为字典

        #验证
        form = LoginForm(data=dict_data,request=request)
        #表单验证
        if form.is_valid():   #判断表单返回的布尔值
            #发送成功
            return res_json(errno=Code.OK)
        else:
            #发送失败
            msg_list = []
            for i in form.errors.get_json_data().values():
                msg_list.append(i[0].get('message'))
            msg_str = '/'.join(msg_list)
            return res_json(errno=Code.PARAMERR,errmsg=msg_str)

#修改密码
class Checkpwd(View):

    def get(self,request):
        title = '修改密码'
        return render(request,'users/chekpwd.html',context={'title':title})

    def post(self,request):
        res = request.body
        mobile = request.user.mobile
        dict_data = json.loads(res)
        old = dict_data.get('old_password')
        new = dict_data.get('new_password')

        if not all([old,new]):
            return res_json('参数不能为空')

        try:
            user = Users.object.get(mobile=mobile)  #返回的是用户名，因为是from users.models import Users中的str函数
        except Exception as e:
            logging.error(e)
            return res_json(errno=Code.PARAMERR, errmsg='账号不存在')
        if user:
            # try:
            #     user.check_password(old)#验证旧的密码
            # except Exception as e:
            #     logger.error(e)
            #     return HttpResponseForbidden('密码有误')
            # password = user.password    #取值
            if not user.check_password(old):   #验证旧的密码,返回布尔值
                return res_json(errno=Code.PARAMERR, errmsg='密码有误')
            if not re.match(r'^[0-9A-Za-z]{6,20}$',new):
                return res_json(errno=Code.PARAMERR, errmsg='密码格式错误')
                # return HttpResponseForbidden('密码格式错误')
            #密码对比
            if old==new:
                return res_json(errno=Code.PARAMERR, errmsg='密码一致')
                # return HttpResponseForbidden('密码一致')
            #修改密码
            user.set_password(new)
            #密码保存
            user.save()
            res = redirect(reverse('users:index'))
            return res_json(errno=Code.OK,errmsg='修改成功')

        else:
            # return HttpResponseForbidden('账号不存在')
            return res_json(errno=Code.PARAMERR, errmsg='账号不存在')


#忘记密码
class Password(View):
    def get(self,request):
        title = '找回密码'
        return render(request,'users/passwd.html',context={'title':title})
    def post(self,request):
        res = request.body
        js_str = json.loads(res)
        password_repeat = js_str.get('password_repeat')
        mobile = js_str.get('mobile')
        sms_code = js_str.get('sms_code')

        # 判断是否为空
        if not all([password_repeat, mobile, sms_code]):
            return HttpResponseForbidden('请填写准确参数')

        # 密码
        if not re.match('^[0-9A-Za-z]{6,20}$', password_repeat):
            return HttpResponseForbidden('密码输入有误')


        # 手机号
        if not re.match('^1[358]\d{9}$', mobile):
            return res_json(errmsg='手机号输入错误')
        if not Users.object.filter(mobile=mobile).count() > 0:  # 判断是否存在，存在返回1
            return HttpResponseForbidden('手机号不存在')

        # 手机验证码
        redis_conn = get_redis_connection('verify')
        sms_code_serve = redis_conn.get('sms_' + mobile)

        # 判断是否为空
        if sms_code_serve is None:
            return res_json(errno=Code.PARAMERR, errmsg='验证码过期')

        # 用完就丢
        redis_conn.delete('sms_'.format(mobile))
        redis_conn.delete('sms_flag_{}'.format(mobile))

        # 判断是否
        if sms_code != sms_code_serve.decode():  # b字节，要解码
            return HttpResponseForbidden('短信验证码错误')

        user = Users.object.get(mobile=mobile)
        if user:
            #修改密码
            user.set_password(password_repeat)
            #密码保存
            user.save()
            res = redirect(reverse('users:index'))
            return res_json(errno=Code.OK,errmsg='修改成功')

        else:
            # return HttpResponseForbidden('账号不存在')
            return res_json(errno=Code.PARAMERR, errmsg='账号不存在')





#退出登录
class OutLogin(View):
    def get(self,request):
        logout(request)
        return redirect('/index')


